package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.U8Service.U8QcProduceService;
import com.yegs.jltqc.VO.RpProduce;
import com.yegs.jltqc.VO.RpStock;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.dao.RpProduceRepository;
import com.yegs.jltqc.dao.RpStockRepository;
import com.yegs.jltqc.service.RpProduceService;
import com.yegs.jltqc.service.RpStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RpStockServiceImpl implements RpStockService {

    @Autowired
    private RpStockRepository rpStockRepository;

    @Override
    public RpStock save(RpStock rpStock) {
        if(rpStock.getId() == null){
            rpStock.setCreateBy(ConcurentCache.getUserName());
            rpStock.setCreateTime(new Date());
        }else {
            rpStock.setUpdateBy(ConcurentCache.getUserName());
            rpStock.setUpdateTime(new Date());
        }
        return rpStockRepository.save(rpStock);
    }

    @Override
    public List<RpStock> list() {
        return rpStockRepository.findAll();
    }

    @Override
    public RpStock get(Long id) {
        return rpStockRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        rpStockRepository.deleteById(id);
    }

    @Override
    public Page<RpStock> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        return rpStockRepository.findAll(request);
    }

    @Override
    public Long getNext(Long id) {
        if(id == null){
            RpStock project = rpStockRepository.findFirstByOrderByIdDesc();
            if(project != null) {
                return project.getId();
            }
        }
        RpStock project = rpStockRepository.findFirstByIdIsAfter(id);
        if(project == null){ project = rpStockRepository.findFirstByOrderByIdDesc(); }
        if(project != null){
            return project.getId();
        }
        return null;
    }

    @Override
    public Long getLast(Long id) {
        if(id == null){
            RpStock project = rpStockRepository.findFirstByOrderByIdDesc();
            if(project != null) {
                return project.getId();
            }
        }
        else{
            RpStock project = rpStockRepository.findFirstByIdBeforeOrderByIdDesc(id);
            if(project == null){ project = rpStockRepository.findFirstByOrderById(); }
            if(project != null){
                return project.getId();
            }
        }
        return null;
    }

}
